<template>
  <div class="photo-quality-view">
    <div class="container">
      <h1 class="page-title">照片质量检测系统</h1>
      
      <!-- 文件上传区域 -->
      <div class="upload-section">
        <div class="upload-area" :class="{ 'drag-over': isDragOver }" 
             @drop="handleDrop" 
             @dragover="handleDragOver" 
             @dragleave="handleDragLeave">
          <div class="upload-content">
            <i class="upload-icon">📸</i>
            <p>拖拽照片文件到此处或点击选择文件</p>
            <input 
              type="file" 
              ref="fileInput" 
              @change="handleFileSelect" 
              accept="image/*" 
              multiple
              style="display: none;"
            />
            <button @click="selectFiles" class="select-btn">
              选择照片
            </button>
          </div>
        </div>
        
        <!-- 质量阈值设置 -->
        <div class="quality-settings">
          <div class="threshold-setting">
            <label>质量阈值:</label>
            <div class="threshold-control">
              <input 
                type="range" 
                v-model="qualityThreshold" 
                min="0" 
                max="1" 
                step="0.1"
                class="threshold-slider"
              />
              <span class="threshold-value">{{ (qualityThreshold * 100).toFixed(0) }}%</span>
            </div>
            <div class="threshold-labels">
              <span>0%</span>
              <span>50%</span>
              <span>100%</span>
            </div>
          </div>
        </div>
        
        <!-- 已选择的文件列表 -->
        <div v-if="selectedFiles.length" class="selected-files">
          <h3>已选择的文件 ({{ selectedFiles.length }})</h3>
          <div class="file-list">
            <div v-for="(file, index) in selectedFiles" :key="index" class="file-item">
              <div class="file-preview">
                <img v-if="file.type.startsWith('image/')" 
                     :src="getFilePreview(file)" 
                     :alt="file.name"
                     class="preview-image" />
                <div v-else class="no-preview">📄</div>
              </div>
              <div class="file-info">
                <span class="file-name">{{ file.name }}</span>
                <span class="file-size">{{ formatFileSize(file.size) }}</span>
                <span class="file-type">{{ file.type }}</span>
              </div>
              <button @click="removeFile(index)" class="remove-btn">×</button>
            </div>
          </div>
          <div class="action-buttons">
            <button @click="detectPhotoQuality" :disabled="loading" class="detect-btn">
              {{ loading ? '检测中...' : '开始质量检测' }}
            </button>
            <button @click="clearFiles" class="clear-btn">清空</button>
          </div>
        </div>
      </div>
      
      <!-- 检测结果 -->
      <div v-if="detectionResults && detectionResults.length" class="results-section">
        <h2>检测结果</h2>
        
        <!-- 结果摘要 -->
        <div class="results-summary">
          <div class="summary-card">
            <div class="summary-item">
              <span class="label">总数量</span>
              <span class="value">{{ detectionResults?.length || 0 }}</span>
            </div>
            <div class="summary-item">
              <span class="label">合格数量</span>
              <span class="value qualified">{{ qualifiedCount }}</span>
            </div>
            <div class="summary-item">
              <span class="label">不合格数量</span>
              <span class="value unqualified">{{ unqualifiedCount }}</span>
            </div>
            <div class="summary-item">
              <span class="label">合格率</span>
              <span class="value" :class="passRateClass">{{ passRate }}%</span>
            </div>
          </div>
        </div>
        
        <!-- 详细结果 -->
        <div class="results-grid">
          <div v-for="(result, index) in detectionResults" :key="index" class="result-card">
            <div class="result-header">
              <h3>{{ selectedFiles[index]?.name || `照片 ${index + 1}` }}</h3>
              <span class="detection-id">ID: {{ result?.detectionId }}</span>
            </div>
            
            <div v-if="result?.error" class="error-message">
              <p>❌ {{ result.error }}</p>
            </div>
            
            <div v-else class="detection-content">
              <!-- 质量状态 -->
              <div class="quality-status" :class="result?.isQualified ? 'qualified' : 'unqualified'">
                <div class="status-icon">
                  {{ result?.isQualified ? '✅' : '❌' }}
                </div>
                <div class="status-text">
                  <span class="status-label">{{ result?.isQualified ? '合格' : '不合格' }}</span>
                  <span class="status-confidence">置信度: {{ formatConfidence(result?.confidence) }}</span>
                </div>
              </div>
              
              <!-- 检测详情 -->
              <div class="detection-details">
                <div class="detail-item">
                  <span class="label">预测标签:</span>
                  <span class="value">{{ result?.predictedLabel }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">质量分数:</span>
                  <span class="value" :class="getQualityScoreClass(result?.qualityScore)">
                    {{ formatConfidence(result?.qualityScore) }}
                  </span>
                </div>
                <div class="detail-item">
                  <span class="label">处理时间:</span>
                  <span class="value">{{ result?.processingTimeMs }}ms</span>
                </div>
                <div class="detail-item">
                  <span class="label">检测时间:</span>
                  <span class="value">{{ formatDateTime(result?.timestamp) }}</span>
                </div>
              </div>
              
              <!-- 所有标签分数 -->
              <div v-if="result?.allScores?.length" class="all-scores">
                <h4>所有标签分数</h4>
                <div class="scores-list">
                  <div v-for="score in result.allScores" :key="score.label" 
                       class="score-item">
                    <div class="score-info">
                      <span class="score-label">{{ score.label }}</span>
                      <span class="score-value">{{ formatConfidence(score.score) }}</span>
                    </div>
                    <div class="score-bar">
                      <div class="score-fill" :style="{ width: `${score.score * 100}%` }"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 统计信息 -->
      <div class="statistics-section">
        <h2>统计信息</h2>
        <div class="statistics-content">
          <div class="statistics-controls">
            <select v-model="statisticsGroupBy" class="group-select">
              <option value="day">按天</option>
              <option value="hour">按小时</option>
              <option value="week">按周</option>
            </select>
            <button @click="loadStatistics" :disabled="statisticsLoading" class="statistics-btn">
              {{ statisticsLoading ? '加载中...' : '加载统计' }}
            </button>
          </div>
          
          <div v-if="statistics" class="statistics-info">
            <div class="statistics-grid">
              <div class="stat-item">
                <span class="stat-label">总检测次数</span>
                <span class="stat-value">{{ statistics.data?.totalDetections }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">合格率</span>
                <span class="stat-value" :class="getPassRateClass(statistics.data?.passRate)">
                  {{ statistics.data?.passRate?.toFixed(2) || '0.00' }}%
                </span>
              </div>
              <div class="stat-item">
                <span class="stat-label">平均置信度</span>
                <span class="stat-value">{{ formatConfidence(statistics.data?.averageConfidence) }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">最高置信度</span>
                <span class="stat-value">{{ formatConfidence(statistics.data?.maxConfidence) }}</span>
              </div>
            </div>
            
            <div v-if="statistics.data?.qualityDistribution?.length" class="quality-distribution">
              <h3>质量分布</h3>
              <div class="distribution-chart">
                <div v-for="dist in statistics.data.qualityDistribution" :key="dist.isQualified" 
                     class="distribution-item">
                  <div class="dist-header">
                    <span class="dist-label">{{ dist.isQualified ? '合格' : '不合格' }}</span>
                    <span class="dist-count">{{ dist.count }} ({{ dist.percentage?.toFixed(1) || '0.0' }}%)</span>
                  </div>
                  <div class="dist-bar">
                    <div class="dist-fill" :style="{ width: `${dist.percentage}%` }"></div>
                  </div>
                  <div class="dist-confidence">
                    平均置信度: {{ formatConfidence(dist.averageConfidence) }}
                  </div>
                </div>
              </div>
            </div>
            
            <div v-if="statistics.data?.recentTrends?.length" class="recent-trends">
              <h3>最近趋势</h3>
              <div class="trends-chart">
                <div v-for="trend in statistics.data.recentTrends" :key="trend.date" 
                     class="trend-item">
                  <div class="trend-date">{{ formatDate(trend.date) }}</div>
                  <div class="trend-stats">
                    <span>总数: {{ trend.totalCount }}</span>
                    <span>合格: {{ trend.qualifiedCount }}</span>
                    <span>合格率: {{ trend.passRate?.toFixed(1) || '0.0' }}%</span>
                  </div>
                  <div class="trend-bar">
                    <div class="trend-fill" :style="{ width: `${trend.passRate}%` }"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 历史记录 -->
      <div class="history-section">
        <h2>检测历史</h2>
        <div class="history-content">
          <div class="history-controls">
            <input v-model="historyStartDate" type="date" class="date-input" />
            <input v-model="historyEndDate" type="date" class="date-input" />
            <select v-model="historyQualifiedStatus" class="status-select">
              <option value="">所有状态</option>
              <option value="true">合格</option>
              <option value="false">不合格</option>
            </select>
            <button @click="loadHistory" :disabled="historyLoading" class="history-btn">
              {{ historyLoading ? '加载中...' : '查询历史' }}
            </button>
          </div>
          
          <div v-if="history" class="history-info">
            <div class="history-summary">
              <p>共找到 {{ history.data?.totalCount }} 条记录，当前显示第 {{ history.data?.pageIndex + 1 }} 页</p>
            </div>
            
            <div class="history-list">
              <div v-for="record in history.data?.records" :key="record.detectionId" 
                   class="history-item">
                <div class="history-header">
                  <span class="history-filename">{{ record.imageFileName }}</span>
                  <span class="history-timestamp">{{ formatDateTime(record.timestamp) }}</span>
                </div>
                <div class="history-content">
                  <div class="history-quality">
                    <span class="quality-status" :class="record.isQualified ? 'qualified' : 'unqualified'">
                      {{ record.isQualified ? '✅ 合格' : '❌ 不合格' }}
                    </span>
                    <span class="quality-score" :class="getQualityScoreClass(record.qualityScore)">
                      {{ formatConfidence(record.qualityScore) }}
                    </span>
                  </div>
                  <div class="history-details">
                    <span>标签: {{ record.predictedLabel }}</span>
                    <span>置信度: {{ formatConfidence(record.confidence) }}</span>
                    <span>处理时间: {{ record.processingTimeMs }}ms</span>
                  </div>
                </div>
              </div>
            </div>
            
            <div v-if="history.data?.totalPages > 1" class="pagination">
              <button @click="loadHistoryPage(history.data.pageIndex - 1)" 
                      :disabled="history.data.pageIndex <= 0" class="page-btn">
                上一页
              </button>
              <span class="page-info">
                第 {{ history.data.pageIndex + 1 }} 页，共 {{ history.data.totalPages }} 页
              </span>
              <button @click="loadHistoryPage(history.data.pageIndex + 1)" 
                      :disabled="history.data.pageIndex >= history.data.totalPages - 1" class="page-btn">
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { PhotoQualityService } from '@/api/photoQuality'

// 响应式数据
const selectedFiles = ref<File[]>([])
const detectionResults = ref<any[]>([])
const statistics = ref<any>(null)
const history = ref<any>(null)
const loading = ref(false)
const statisticsLoading = ref(false)
const historyLoading = ref(false)
const isDragOver = ref(false)
const qualityThreshold = ref(0.5) // 降低默认阈值，让更多图片能够合格
const statisticsGroupBy = ref('day')
const historyStartDate = ref('')
const historyEndDate = ref('')
const historyQualifiedStatus = ref('')
const currentPage = ref(0)

// 模板引用
const fileInput = ref<HTMLInputElement>()

// 计算属性
const qualifiedCount = computed(() => {
  if (!detectionResults.value) return 0
  return detectionResults.value.filter(r => r?.isQualified).length
})

const unqualifiedCount = computed(() => {
  if (!detectionResults.value) return 0
  return detectionResults.value.filter(r => !r?.isQualified).length
})

const passRate = computed(() => {
  if (!detectionResults.value || !detectionResults.value.length) return 0
  return (qualifiedCount.value / detectionResults.value.length * 100).toFixed(2)
})

const passRateClass = computed(() => {
  const rate = parseFloat(passRate.value.toString())
  if (rate >= 80) return 'excellent'
  if (rate >= 60) return 'good'
  if (rate >= 40) return 'fair'
  return 'poor'
})

// 文件处理
const selectFiles = () => {
  fileInput.value?.click()
}

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files) {
    selectedFiles.value = Array.from(target.files)
  }
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
  
  if (event.dataTransfer?.files) {
    const files = Array.from(event.dataTransfer.files).filter(file => 
      file.type.startsWith('image/')
    )
    selectedFiles.value = [...selectedFiles.value, ...files]
  }
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = () => {
  isDragOver.value = false
}

const removeFile = (index: number) => {
  selectedFiles.value.splice(index, 1)
}

const clearFiles = () => {
  selectedFiles.value = []
  detectionResults.value = []
}

const getFilePreview = (file: File): string => {
  return URL.createObjectURL(file)
}

// 质量检测功能
const detectPhotoQuality = async () => {
  if (selectedFiles.value.length === 0) return
  
  loading.value = true
  detectionResults.value = []
  
  try {
    if (selectedFiles.value.length === 1) {
      // 单张照片检测
      const result = await PhotoQualityService.detectPhotoQuality(selectedFiles.value[0], {
        qualityThreshold: qualityThreshold.value
      })
      detectionResults.value = result?.data ? [result.data] : []
    } else {
      // 批量检测
      const result = await PhotoQualityService.detectBatchPhotoQuality(selectedFiles.value, {
        qualityThreshold: qualityThreshold.value
      })
      detectionResults.value = result?.data?.results || []
    }
    
  } catch (error: any) {
    console.error('质量检测失败:', error)
    alert('质量检测失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 统计信息加载
const loadStatistics = async () => {
  statisticsLoading.value = true
  
  try {
    statistics.value = await PhotoQualityService.getQualityStatistics({
      startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 最近30天
      endDate: new Date(),
      groupBy: statisticsGroupBy.value
    })
  } catch (error: any) {
    console.error('加载统计信息失败:', error)
    alert('加载统计信息失败: ' + error.message)
  } finally {
    statisticsLoading.value = false
  }
}

// 历史记录加载
const loadHistory = async () => {
  historyLoading.value = true
  
  try {
    history.value = await PhotoQualityService.getDetectionHistory({
      startDate: historyStartDate.value ? new Date(historyStartDate.value) : null,
      endDate: historyEndDate.value ? new Date(historyEndDate.value) : null,
      isQualified: historyQualifiedStatus.value ? historyQualifiedStatus.value === 'true' : null,
      pageIndex: currentPage.value,
      pageSize: 10
    })
  } catch (error: any) {
    console.error('加载历史记录失败:', error)
    alert('加载历史记录失败: ' + error.message)
  } finally {
    historyLoading.value = false
  }
}

const loadHistoryPage = async (pageIndex: number) => {
  currentPage.value = pageIndex
  await loadHistory()
}

// 工具函数
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatConfidence = (confidence: number): string => {
  return `${(confidence * 100).toFixed(2)}%`
}

const formatDateTime = (date: string | Date): string => {
  return new Date(date).toLocaleString('zh-CN')
}

const formatDate = (date: string | Date): string => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const getQualityScoreClass = (score: number): string => {
  if (score >= 0.8) return 'excellent'
  if (score >= 0.6) return 'good'
  if (score >= 0.4) return 'fair'
  return 'poor'
}

const getPassRateClass = (rate: number): string => {
  if (rate >= 80) return 'excellent'
  if (rate >= 60) return 'good'
  if (rate >= 40) return 'fair'
  return 'poor'
}

// 组件挂载时加载统计信息
onMounted(() => {
  loadStatistics()
  
  // 设置默认日期范围
  const today = new Date()
  const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
  historyStartDate.value = thirtyDaysAgo.toISOString().split('T')[0]
  historyEndDate.value = today.toISOString().split('T')[0]
})
</script>

<style scoped>
.photo-quality-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

/* 上传区域样式 */
.upload-section {
  margin-bottom: 40px;
}

.upload-area {
  border: 2px dashed #ccc;
  border-radius: 10px;
  padding: 40px;
  text-align: center;
  transition: all 0.3s ease;
  cursor: pointer;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: #007bff;
  background-color: #f8f9fa;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.upload-icon {
  font-size: 48px;
}

.select-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.select-btn:hover {
  background-color: #0056b3;
}

/* 质量设置样式 */
.quality-settings {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.threshold-setting {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.threshold-control {
  display: flex;
  align-items: center;
  gap: 15px;
}

.threshold-slider {
  flex: 1;
  height: 6px;
  border-radius: 3px;
  background: #ddd;
  outline: none;
  -webkit-appearance: none;
}

.threshold-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #007bff;
  cursor: pointer;
}

.threshold-value {
  font-weight: 600;
  color: #007bff;
  min-width: 50px;
}

.threshold-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

/* 已选择文件列表 */
.selected-files {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.file-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-bottom: 15px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  border: 1px solid #ddd;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.file-preview {
  width: 60px;
  height: 60px;
  border-radius: 5px;
  overflow: hidden;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-preview {
  font-size: 24px;
  color: #666;
}

.file-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.file-name {
  font-weight: 500;
  color: #333;
}

.file-size, .file-type {
  font-size: 12px;
  color: #666;
}

.remove-btn {
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  cursor: pointer;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.detect-btn {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
}

.detect-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.clear-btn {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 5px;
  cursor: pointer;
}

/* 结果区域样式 */
.results-section {
  margin-bottom: 40px;
}

.results-summary {
  margin-bottom: 20px;
}

.summary-card {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.summary-item .label {
  font-size: 14px;
  color: #666;
}

.summary-item .value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.summary-item .value.qualified {
  color: #28a745;
}

.summary-item .value.unqualified {
  color: #dc3545;
}

.summary-item .value.excellent {
  color: #28a745;
}

.summary-item .value.good {
  color: #17a2b8;
}

.summary-item .value.fair {
  color: #ffc107;
}

.summary-item .value.poor {
  color: #dc3545;
}

.results-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.result-card {
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.detection-id {
  font-size: 12px;
  color: #666;
}

.error-message {
  color: #dc3545;
  font-weight: 500;
}

.detection-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 质量状态样式 */
.quality-status {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border-radius: 8px;
  border: 2px solid;
}

.quality-status.qualified {
  background-color: #d4edda;
  border-color: #28a745;
  color: #155724;
}

.quality-status.unqualified {
  background-color: #f8d7da;
  border-color: #dc3545;
  color: #721c24;
}

.status-icon {
  font-size: 24px;
}

.status-text {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.status-label {
  font-weight: 600;
  font-size: 18px;
}

.status-confidence {
  font-size: 14px;
  opacity: 0.8;
}

/* 检测详情样式 */
.detection-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item .label {
  font-weight: 500;
  color: #333;
}

.detail-item .value {
  font-weight: 600;
}

.detail-item .value.excellent {
  color: #28a745;
}

.detail-item .value.good {
  color: #17a2b8;
}

.detail-item .value.fair {
  color: #ffc107;
}

.detail-item .value.poor {
  color: #dc3545;
}

/* 分数列表样式 */
.all-scores h4 {
  margin-bottom: 10px;
  color: #333;
}

.scores-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.score-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.score-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score-label {
  font-weight: 500;
}

.score-value {
  font-size: 14px;
  color: #666;
}

.score-bar {
  height: 8px;
  background-color: #e9ecef;
  border-radius: 4px;
  overflow: hidden;
}

.score-fill {
  height: 100%;
  background-color: #007bff;
  transition: width 0.3s ease;
}

/* 统计信息样式 */
.statistics-section,
.history-section {
  margin-bottom: 40px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.statistics-controls,
.history-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.group-select,
.status-select,
.date-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.statistics-btn,
.history-btn {
  background-color: #17a2b8;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.statistics-btn:disabled,
.history-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.stat-item {
  background-color: white;
  padding: 15px;
  border-radius: 5px;
  text-align: center;
  border: 1px solid #ddd;
}

.stat-label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  display: block;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.stat-value.excellent {
  color: #28a745;
}

.stat-value.good {
  color: #17a2b8;
}

.stat-value.fair {
  color: #ffc107;
}

.stat-value.poor {
  color: #dc3545;
}

/* 质量分布样式 */
.quality-distribution h3,
.recent-trends h3 {
  margin-bottom: 15px;
  color: #333;
}

.distribution-chart,
.trends-chart {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.distribution-item,
.trend-item {
  background-color: white;
  padding: 15px;
  border-radius: 5px;
  border: 1px solid #ddd;
}

.dist-header,
.trend-date {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.dist-label {
  font-weight: 500;
}

.dist-count {
  font-size: 14px;
  color: #666;
}

.dist-bar,
.trend-bar {
  height: 10px;
  background-color: #e9ecef;
  border-radius: 5px;
  overflow: hidden;
  margin-bottom: 5px;
}

.dist-fill,
.trend-fill {
  height: 100%;
  background-color: #007bff;
  transition: width 0.3s ease;
}

.dist-confidence {
  font-size: 12px;
  color: #666;
}

.trend-stats {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

/* 历史记录样式 */
.history-summary {
  margin-bottom: 15px;
  padding: 10px;
  background-color: white;
  border-radius: 5px;
  border: 1px solid #ddd;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  background-color: white;
  padding: 15px;
  border-radius: 5px;
  border: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-header {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.history-filename {
  font-weight: 500;
}

.history-timestamp {
  font-size: 12px;
  color: #666;
}

.history-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
  align-items: center;
}

.history-quality {
  display: flex;
  gap: 10px;
  align-items: center;
}

.quality-status.qualified {
  color: #28a745;
}

.quality-status.unqualified {
  color: #dc3545;
}

.history-details {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #666;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.page-btn {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:disabled {
  background-color: #adb5bd;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}
</style>
